package com.zcsy.manage.web.base;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellBuilding;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CellRegion;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Title: CellRegionController.java
 * @Package： com.zcsy.manage.web.base 
 * @Description: 小区区域控制层
 * @author lilan 1063972142@qq.com
 * @Copyright: 2015 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年6月6日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/cellRegion")
public class CellRegionController {
	@Autowired
	private ICellRegionService cellRegionService;
	
	@Autowired
	private ICellInfoService cellInfoService;
	
	@Autowired
	private ICellBuildingService cellBuildingService;
	
	@Autowired
	private ICellUnitService cellUnitService;
	
	@Autowired
	private ICellHouseService cellHouseService;

	@Autowired
	private IDictService dictService;
	
    /**
     * @Description 返回小区区域查询列表<br>
     * @param model 
     * @param pNo 当前页面
     * @param name 区域名字
     * @param req 用户请求
     * @return 返回小区区域查询列表
     * @author lilan 1063972142@qq.com
     * @date 2016年4月6日
     * @see 
     */
    @RequestMapping(value="cellRegionList" , method = RequestMethod.GET)
    public String cellRegionList(Model model, Integer pNo, Integer pSize, String name, HttpServletRequest req){
    	
	    if(pNo == null){
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        CellRegion cellRegion = new CellRegion();
        
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellid = user.getCurrentCell().getId();
        cellRegion.setCellId(cellid);
        	
        if (StringUtils.isNotEmpty(name)) {
            cellRegion.setName(name);
        }

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        List<CellRegion> cellRegions = cellRegionService.selectByKeyword(cellRegion);
        PageInfo<CellRegion> Region = new PageInfo<CellRegion>(cellRegions);
        model.addAttribute("cellRegion", Region);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("pSize", pSize);
        model.addAttribute("name", name);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "base/cellregion/cellRegionList";
    }
    
    /**
     * @Description 返回新增或编辑小区区域页面<br>
     * type = 1:新增页面
     * type = 2:编辑页面
     * @param model
     * @param id 主键id id=0新增 ；id!=0编辑
     * @return 返回新增或编辑小区区域页面
     * @author lilan 1063972142@qq.com
     * @date 2016年4月6日
     * @see
     */
    @RequestMapping(value = "editCellRegion", method = RequestMethod.GET)
    public String selectById(Model model, String id) {
    	 try {
             if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                 model.addAttribute("type", Constants.SAVE_TYPE);
             } else {
                 CellRegion cellRegion = cellRegionService.selectByPrimaryKey(id);
                 if(cellRegion != null){
                	 model.addAttribute("type", Constants.EDIT_TYPE);
                 	model.addAttribute("cellRegion", cellRegion);
                 	model.addAttribute("regioncellId", cellRegion.getCellId());
                 }
             }
             List<CellInfo>  cellInfos = cellInfoService.getAllCellInfo();
 			model.addAttribute("cellInfos",cellInfos);
             
         } catch (Exception e) {
         }
    	 
         return "base/cellregion/cellRegionEdit";
     }

    /**
     * @Description 保存和更新小区区域方法
     * @param name 区域名字
     * @param id 当前记录id
     * @param cellid 小区id
     * @param memo 备注
     * @param req 用户请求
     * @return 返回结果1：成功 0： 失败
     * @author lilan 1063972142@qq.com
     * @date 2016年4月6日
     * @see
     */
     @RequestMapping(value="saveOrUpdateCellRegion" , method = RequestMethod.POST)
     @ResponseBody
     public RequestJson saveOrUpdate(String name,String id,
            String memo, Integer sort, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        CellRegion cellRegion = new CellRegion();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellid = user.getCurrentCell().getId();
        CellInfo cellInfo = null;
		if (!StringUtil.isEmptyString(cellid)) {
			cellInfo = cellInfoService.selectByPrimaryKey(cellid);
		}
        cellRegion.setName(name);
        cellRegion.setSort(sort);
        cellRegion.setUserAccount(user.getLoginname());
        // cellRegion.setMemo(memo);
        try {
            // 检验名称是否存在
            boolean isUpdate = (id != null && !"0".equals(id));
            boolean nameExists = cellRegionService.isNameExists(isUpdate ? id : null, cellid, name);
            if(nameExists) {
                result.setSuccess(false);
                result.setMsg("区域名称已存在");
            } else {
                if (isUpdate) {
                    cellRegion.setId(id);
                    cellRegion.setUpdateTime(new Date());
                    cellRegionService.update(cellRegion);
                    LogUtils.insertLog("用户编辑小区区域信息", user.getId(), req);
                } else {
                    cellRegion.setId(UniqueNumberUtils.get18UniqueNumber());
                    cellRegion.setSendTime(new Date());
                    cellRegion.setCellId(cellid);
                    if (cellInfo != null) {
                        cellRegion.setCellName(cellInfo.getCellName());
                    }
                    /*Integer flag = */cellRegionService.insert(cellRegion);
                    /*if (flag == Constants.SUCCESS && cellInfo.getIsUsed() != Constants.IS_USED) {
                    	CellInfo record = new CellInfo();
                    	record.setIsUsed(Constants.IS_USED);
                    	record.setUpdateTime(new Date());
                    	record.setId(cellInfo.getId());
						cellInfoService.updateIsUsed(record);
					}*/
                    LogUtils.insertLog("用户新增小区区域信息", user.getId(), req);
                }
                result.setSuccess(true);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        
        return result;
    }
    
     /**
      * @Description 根据小区区域id可以同时删除多条区域信息
      * @param ids 小区区域对象id数组
      * @param req 用户请求
      * @return 删除结果RequestJson
      * @author lilan 1063972142@qq.com
      * @date 2016年4月6日
      * @see
      */
    @RequestMapping(value = "deleteByPrimaryKey", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteByPrimaryKey(String ids,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
			String keys[] = ids.split("\\,");
				for (int i = 0; i < keys.length; i++ ) {
					List<CellBuilding> cellBuildings = cellBuildingService.getCellBuildingByRegionId(keys[i]);
					CellRegion cellRegion = cellRegionService.selectByPrimaryKey(keys[i]);
				    if(CollectionUtils.isEmpty(cellBuildings)){
				    	cellRegionService.deleteByPrimaryKey(keys[i]);
				    	result.setSuccess(true);
				    	LogUtils.insertLog("用户删除小区区域信息", user.getId(), req);
				}else{
					result.setMsg(cellRegion.getName() + "区域已被引用，不能删除!");
					result.setSuccess(false);
				}
			}
		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        
        return result;
    }
    
	/**
	 * @Description 根据排序实现置顶功能，即修改当前排序为最大排序值加1，并且更新修改时间<br>
	 * @param id 商品id
	 * @param req 用户请求
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月3日
	 * @see 
	 */
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id,HttpServletRequest req){
        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
        	CellRegion cellRegion = cellRegionService.selectByPrimaryKey(id);
        	if(cellRegion != null){
        		cellRegion.setUpdateTime(DateUtils.getDate());
        		cellRegionService.updateSort(cellRegion);
        		LogUtils.insertLog("用户删除小区区域信息", user.getId(), req);
        	}
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }
}
